import { computed, ref } from "vue";
import { useAppStore } from "@/stores/modules/app";

// 默认Tab列表配置
export const defaultTabList = [
  {
    id: "home",
    text: "首页",
    icon: "home",
    activeIcon: "home-fill",
    path: "/pages/index/index",
    badge: 0,
  },
  {
    id: "chat",
    text: "AI对话",
    icon: "chat",
    activeIcon: "chat-fill",
    path: "/pages/chat/index",
    badge: 0,
  },
  {
    id: "robot",
    text: "示范机器人",
    icon: "android-circle-fill",
    activeIcon: "android-circle-fill",
    path: "/pages/robot/index",
    badge: 0,
  },
  {
    id: "profile",
    text: "我的",
    icon: "account",
    activeIcon: "account-fill",
    path: "/pages/profile/index",
    badge: 0,
  },
];

// Tabbar配置（供Layout组件使用）
export const tabbarConfig = {
  list: defaultTabList,
  fixed: true,
  backgroundColor: "#ffffff",
  activeColor: "#007AFF",
  inactiveColor: "#8E8E93",
  borderTopColor: "rgba(0, 0, 0, 0.05)",
};

// Props 定义
export const tabbarProps = {
  modelValue: {
    type: Number,
    default: 0,
  },
  tabList: {
    type: Array,
    default: () => defaultTabList,
  },
  activeColor: {
    type: String,
    default: "#007AFF",
  },
  inactiveColor: {
    type: String,
    default: "#8E8E93",
  },
  fixed: {
    type: Boolean,
    default: true,
  },
};

// Emits 定义
export const tabbarEmits = ["update:modelValue", "change", "tabClick"];

export function useTabbarData(props, emit) {
  // Store
  const appStore = useAppStore();

  // 响应式数据
  const isNavigating = ref(false);

  // 计算属性
  const currentIndex = computed({
    get: () => props.modelValue,
    set: (value) => emit("update:modelValue", value),
  });

  const safeAreaBottom = computed(() => appStore.safeArea.bottom || 0);

  // 方法
  const handleTabClick = (item, index) => {
    if (currentIndex.value === index) return;
    if (isNavigating.value) {
      console.log("正在导航中，忽略此次点击");
      return;
    }

    currentIndex.value = index;
    emit("change", { item, index });
    emit("tabClick", { item, index });

    // 如果有路径，则进行页面跳转
    if (item.path) {
      isNavigating.value = true;

      // 对H5环境特殊处理
      // #ifdef H5
      setTimeout(() => {
        uni.navigateTo({
          url: item.path,
          success: () => {
            console.log("页面跳转成功:", item.path);
            setTimeout(() => {
              isNavigating.value = false;
            }, 300);
          },
          fail: (err) => {
            console.error("H5跳转失败:", err);
            isNavigating.value = false;
          },
        });
      }, 100);
      // #endif

      // 其他平台使用redirectTo
      // #ifndef H5
      uni.redirectTo({
        url: item.path,
        success: () => {
          console.log("页面跳转成功:", item.path);
          setTimeout(() => {
            isNavigating.value = false;
          }, 500);
        },
        fail: (err) => {
          console.error("Tab跳转失败:", err);
          // 降级处理：如果redirectTo失败，使用navigateTo
          uni.navigateTo({
            url: item.path,
            success: () => {
              console.log("降级跳转成功:", item.path);
              setTimeout(() => {
                isNavigating.value = false;
              }, 500);
            },
            fail: (err2) => {
              console.error("降级跳转也失败:", err2);
              isNavigating.value = false;
            },
          });
        },
      });
      // #endif
    }
  };

  const setBadge = (tabId, count) => {
    const tab = props.tabList.find((item) => item.id === tabId);
    if (tab) {
      tab.badge = count;
    }
  };

  const setCurrentIndex = (index) => {
    currentIndex.value = index;
  };

  return {
    // 响应式数据
    isNavigating,

    // 计算属性
    currentIndex,
    safeAreaBottom,

    // 方法
    handleTabClick,
    setBadge,
    setCurrentIndex,
  };
}
